package com.lrh.netty;


import com.lrh.config.NettyConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// 通道初始化对象
@Component
public class WebSocketChannelInit extends ChannelInitializer {

    @Autowired
    NettyConfig nettyConfig;
    @Autowired
    WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        // HTTP协议的支持  http的编解码器
        pipeline.addLast(new HttpServerCodec());
        // 大数据流的智齿
        pipeline.addLast(new ChunkedWriteHandler());
        // 一个请求分三步  request line / request header / message body
        // HttpObjectAggregator将多个信息转化成单一的request或者response的对象
        pipeline.addLast(new HttpObjectAggregator(8000));
        // http 协议 升级为websocket协议  (websocket支持)
        pipeline.addLast(new WebSocketServerProtocolHandler(nettyConfig.getPath()));
        // 自定义
        pipeline.addLast(webSocketHandler);
    }
}
